<template>
    <div id="changeEmail">
        <MipLightbox>
            <template v-slot:slot1>
                <el-button type="primary" class="modelfy_row changeEmail"
                           @click="dialogFormVisible = true">修改邮箱
                </el-button>

                <!-- Form -->
                <el-dialog title="修改邮箱" :visible.sync="dialogFormVisible" width="35%">

                    <div style="margin-bottom: 20px;height: 30px">
                        <div style="float: left;margin-left: 40px">当前邮箱：{{$store.state.admin.adminEmail}}</div>
                    </div>


                    <el-form :model="ruleForm" :rules="rules" ref="ruleForm"
                             class="demo-ruleForm">
                        <el-form-item label="验证码" :label-width="formLabelWidth" prop="userVerificationCode" class="phone">
                            <el-input type="text" autocomplete="off" placeholder="输入验证码" v-model="ruleForm.userVerificationCode"/>
                            <div class="btn">
                                <el-button @click="oldEmailVerification" :disabled="disabled1">
                                    <span v-if="!disabled1">获取验证码</span>
                                    <span v-if="disabled1">({{ruleForm.num1}})获取验证码</span>
                                </el-button>
                            </div>
                        </el-form-item>
                        <el-form-item label="新的邮箱" :label-width="formLabelWidth" prop="newEmail">
                            <el-input v-model="ruleForm.newEmail" placeholder="请输入新的邮箱"
                                      autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="验证码" :label-width="formLabelWidth" prop="userNewVerificationCode" class="phone">
                            <el-input type="text" autocomplete="off" placeholder="输入短信验证码" v-model="ruleForm.userNewVerificationCode"/>
                            <div class="btn">
                                <el-button @click="newEmailVerification" :disabled="disabled2">
                                    <span v-if="!disabled2">获取验证码</span>
                                    <span v-if="disabled2">({{ruleForm.num2}})获取验证码</span>
                                </el-button>
                            </div>
                        </el-form-item>

                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
                        <el-button @click="dialogFormVisible = false">取 消</el-button>
                    </div>
                </el-dialog>
            </template>
        </MipLightbox>
    </div>
</template>

<script>

    import {Button, Dialog, Form, FormItem, Input} from "element-ui"
    import MipLightbox from "@/components/miplightbox/MipLightbox";
    import {post} from "@/request/AxiosMAX";
    import { MessageBox } from 'element-ui';
    export default {
        name: "ChangeEmail",
        data() {
            var validate1 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入验证码'));
                } else {
                    if (this.ruleForm.verificationCode !== '') {
                        this.$refs.ruleForm.validateField('verificationCode');
                    }
                    callback();
                }
            };
            var validate2 = (rule, value, callback) => {
                const $regEmal =/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
                if (value == '') {
                    callback(new Error('请输入新的邮箱地址'));
                } else if (!$regEmal.test(value)) {
                    callback(new Error('邮箱不合法'));
                }
                callback();
            };
            var validate3 = (rule, value, callback) => {
                if (value == '') {
                    callback(new Error('请输入验证码'));
                } else {
                    callback();
                }
            }
            return {
                dialogFormVisible: false,
                formLabelWidth: '120px',
                disabled1:false,
                disabled2:false,
                ruleForm: {
                    //后台接收的验证码
                    verificationCode:'',
                    //用户输入的验证吗
                    userVerificationCode: '',
                    newEmail: '',
                    //新手机号用户输入的验证码
                    userNewVerificationCode:'',
                    //后台介绍的验证码
                    checkVerificationCode: '',
                    num1:60,
                    num2:60,
                },
                rules: {
                    userVerificationCode: [
                        {validator: validate1, trigger: 'blur'}
                    ],
                    newEmail: [
                        {validator: validate2, trigger: 'blur'}
                    ],
                    userNewVerificationCode: [
                        {validator: validate3, trigger: 'blur'}
                    ]
                }
            }
        },
        components: {
            MipLightbox,
            "el-button": Button,
            "el-dialog": Dialog,
            "el-form": Form,
            "el-form-item": FormItem,
            "el-input": Input,
        },
        methods: {
            //修改邮箱的方法
            submitForm(ruleForm) {
                MessageBox.confirm('修改邮箱需要重新登录, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$refs[ruleForm].validate((valid) => {
                        if (valid){
                            if (this.ruleForm.verificationCode===this.ruleForm.userVerificationCode){
                                if (this.ruleForm.checkVerificationCode===this.ruleForm.userNewVerificationCode){
                                    let user = this.$store.state.admin;
                                    //修改手机号
                                    user.adminEmail = this.ruleForm.newEmail;
                                    post("/api/Studies_to_travel/admin/updateSelective",user)
                                        .then(res=>{
                                            if (res.code===0){
                                                //关闭
                                                this.dialogFormVisible = false;
                                                //清楚表单数据
                                                this.$refs[ruleForm].resetFields();
                                                this.$message({
                                                    message: '修改成功~',
                                                    type: 'success'
                                                });
                                                //清空本地缓存
                                                localStorage.clear();
                                                //重新登录
                                                this.$router.push("/login");
                                            }else {
                                                this.$message({
                                                    message: '修改失败~',
                                                    type: 'error'
                                                });
                                            }
                                        })
                                        .catch(err=>{
                                            console.info(err);
                                            this.$message({
                                                message: '网络错误~',
                                                type: 'error'
                                            });
                                        });
                                }else {
                                    this.$message({
                                        message: '验证码错误~',
                                        type: 'error'
                                    });
                                }
                            }else {
                                this.$message({
                                    message: '验证码错误~',
                                    type: 'error'
                                });
                            }

                        }else {
                            this.$message({
                                message: '请完善必填项~',
                                type: 'error'
                            });
                        }
                    })
                }).catch((err) => {
                    console.info(err)
                });

            },
            //获得旧手机的验证码
            oldEmailVerification(){

                //定时器
                let num = 60;
                this.disabled1=true;
                let  setInter=setInterval(()=>{
                    this.ruleForm.num1 = --num;
                    if(this.ruleForm.num1===0){
                        this.disabled1=false;
                        clearInterval(setInter);
                    }
                },1000)
                post("/api/Studies_to_travel/BaseRegister/emailVerification",{email:this.$store.state.admin.adminEmail})
                    .then(res=>{
                        if (res.code===0){
                            //获得旧手机的验证码
                            this.ruleForm.verificationCode=res.data;
                        }
                    })
                    .catch(err=>{
                        console.info(err);
                    })
            },
            //获得新手机的验证码
            newEmailVerification(){
                //定时器
                let num = 60;
                this.disabled2=true;
                let  setInter=setInterval(()=>{
                    this.ruleForm.num2 = --num;
                    if(this.ruleForm.num2===0){
                        this.disabled2=false;
                        clearInterval(setInter);
                    }
                },1000)
                post("/api/Studies_to_travel/BaseRegister/emailVerification",{email:this.ruleForm.newEmail})
                    .then(res=>{
                        if (res.code===0){
                            //获得新手机的验证码
                            this.ruleForm.checkVerificationCode=res.data;
                        }
                    })
                    .catch(err=>{
                        console.info(err);
                    })
            }

        }
    }
</script>

<style scoped>

    .modelfy_row {
        width: 280px;
        margin: 1% 0% 1% 6%;
    }

    .btn {
        margin-left: 252px;
        margin-top: -40px;
    }
    .phone {
        width: 360px;
    }


</style>
